<template>
    <div class="widget-form-container">
        <el-form :size="data.config.size" :label-position="data.config.labelPosition" :label-width="data.config.labelWidth + 'px'">

            <draggable
                class="widget-form-list"
                v-model="data.list"
                v-bind="{group:'people', ghostClass: 'ghost'}"
                @end="handleMoveEnd"
                @add="handleWidgetAdd"
            >

                <template v-for="(element, index) in data.list">
                    <template v-if="element.type == 'BaseGrid'">
                        <div v-if="element && element.key" class="widget-grid-container data-grid" :key="index" style="position: relative;">
                            <el-row
                                class="widget-grid"
                                type="flex"
                                :class="{active: selectWidget.key == element.key}"
                                :gutter="element.options.gutter ? element.options.gutter : 0"
                                :justify="element.options.justify"
                                :align="element.options.align"
                               >
                                <el-col v-for="(col, colIndex) in element.columns" :key="colIndex" :span="col.span ? col.span : 0">
                                    <div style="border: 1px dashed #999;">
                                        <draggable
                                            class="widget-form-list"
                                            style="padding-bottom: 50px;"
                                            v-model="col.list"
                                            filter="widget-grid-container"
                                            v-bind="{group:'people', ghostClass: 'ghost'}"
                                            @end="handleMoveEnd"
                                            @add="handleWidgetColAdd($event, element, colIndex)"
                                        >
                                            <div  v-for="(el, i) in col.list" :key="i">
                                                <widget-form-item 
                                                  @click.native.stop="handleSelectGridWidget(index,colIndex,i)" 
                                                  :element="el"
                                                  :select.sync="selectWidget" 
                                                  :index="i" 
                                                  :data="col"/>
                                            </div>
                                        </draggable>
                                    </div>
                                </el-col>

                            </el-row>
                        </div>
                    </template>
                    <template v-if="element.type == 'GridRow'">
                        <div v-if="element && element.key" class="widget-grid-container data-grid GridRow" :key="element.key" style="position: relative;">
                            <draggable
                                class="widget-form-list"
                                style="padding-bottom: 20px;"
                                v-model="element.list"
                                filter="widget-grid-container"
                                v-bind="{group:'people', ghostClass: 'ghost'}"
                                @end="handleMoveEnd"
                                @add="handleWidgetGridAdd($event, element)"
                            >
                                <griddrag :options="options" :grid-width="gridWidth" style="min-height: 200px;">
                                    <griddrag-item @click.native.stop="handleSelectRridWidget(index,i)" v-for="(el, i) in element.list" :item="el.grid" :key="el.key">
                                        <widget-form-item
                                            :class="{'grid-row-item':el.type=='BaseMoban'}"
                                            :key="el.key"
                                            :element="el"
                                            :select.sync="selectWidget"
                                            :index="i"
                                            :f-index="index"
                                            :is-grid="true"
                                            :data="data"/>
                                    </griddrag-item>
                                </griddrag>
                            </draggable>

                            <el-button title="删除" style="bottom: 0px;" @click.stop="handleWidgetDelete(index)" class="widget-action-delete" v-if="selectWidget.key == element.key" circle plain type="danger">
                                <i class="iconfont2 icon-trash" />
                            </el-button>
                        </div>
                    </template>
                    <template v-else>

                        <widget-form-item @click.native.stop="handleSelectWidget(index)" v-if="element && element.key" :key="element.key" :element="element" :select.sync="selectWidget" :index="index" :data="data"/>

                    </template>
                </template>
            </draggable>
        </el-form>
    </div>
</template>

<script>
import Template from './template'
import Draggable from 'vuedraggable'
import WidgetFormItem from './WidgetFormItem'
import deepClone from '@/utils/deepClone'
export default {
    components: {
        Draggable,
        WidgetFormItem,
        ...Template
    },
    props: ['data', 'select', 'activeRect'],
    data() {
        return {
            selectWidget: this.select,
            options: {
                margins: [0, 0],
                pushing: true,
                floating: true,
                isMobile: false,
                draggable: { enabled: true },
                resizable: { enabled: true }
            }
        }
    },
    computed: {
        gridWidth() {
            return document.documentElement.offsetWidth - 615
        }
    },
    watch: {
        select(val) {
            this.selectWidget = val
        },
        selectWidget: {
            handler(val) {
                this.$emit('update:select', val)
            },
            deep: true
        }
    },
    mounted() {
        document.body.ondrop = function(event) {
            const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
            if (isFirefox) {
                event.preventDefault()
                event.stopPropagation()
            }
        }
    },
    methods: {
        handleMoveEnd({ newIndex, oldIndex }) {
            // console.log('index', newIndex, oldIndex)
        },
        handleSelectWidget(index) {
            this.selectWidget = this.data.list[index]
        },
        handleSelectRridWidget(index, cindex) {
            this.selectWidget = this.data.list[index].list[cindex]
        },
        handleSelectGridWidget(index,col,i){
            this.selectWidget = this.data.list[index].columns[col].list[i]
        },
        handleWidgetAdd(evt) {
            const newIndex = evt.newIndex
            const to = evt.to
            this.data.list = deepClone(this.data.list)
            // 为拖拽到容器的元素添加唯一 key
            const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
            this.$set(this.data.list, newIndex, {
                ...this.data.list[newIndex],
                options: {
                    ...this.data.list[newIndex].options,
                    remoteFunc: 'func_' + key
                },
                key,
                // 绑定键值
                model: this.data.list[newIndex].type + '_' + key,
                rules: []
            })

            if (this.data.list[newIndex].type === 'BaseGrid') {
                this.$set(this.data.list, newIndex, {
                    ...this.data.list[newIndex],
                    columns: this.data.list[newIndex].columns.map(item => ({ ...item }))
                })
            }

            this.selectWidget = this.data.list[newIndex]
        },
        handleWidgetGridAdd($event, el) {
            const newIndex = $event.newIndex
            const to = $event.to
            // this.$set(this.data.list,)
            // 为拖拽到容器的元素添加唯一 key
            const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)

            this.$set(el.list, newIndex, {
                ...el.list[newIndex],
                options: {
                    ...el.list[newIndex].options,
                    remoteFunc: 'func_' + key
                },

                key,
                // 绑定键值
                model: el.list[newIndex].type + '_' + key,
                rules: []
            })

            this.selectWidget = el.list[newIndex]
            this.data.list = deepClone(this.data.list)
        },
        handleWidgetColAdd($event, row, colIndex) {
            const newIndex = $event.newIndex
            const oldIndex = $event.oldIndex
            const item = $event.item
            
            // 防止布局元素的嵌套拖拽
            if (item.className.indexOf('data-grid') >= 0) {
                // 如果是列表中拖拽的元素需要还原到原来位置
                item.tagName === 'DIV' && this.data.list.splice(oldIndex, 0, row.columns[colIndex].list[newIndex])

                row.columns[colIndex].list.splice(newIndex, 1)

                return false
            }

            const key = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)

            this.$set(row.columns[colIndex].list, newIndex, {
                ...row.columns[colIndex].list[newIndex],
                options: {
                    ...row.columns[colIndex].list[newIndex].options,
                    remoteFunc: 'func_' + key
                },
                key,
                // 绑定键值
                model: row.columns[colIndex].list[newIndex].type + '_' + key,
                rules: []
            })
            // this.data.list = deepClone(this.data.list)
            this.selectWidget = row.columns[colIndex].list[newIndex]
        },
        handleWidgetDelete(index) {
            if (this.data.list.length - 1 === index) {
                if (index === 0) {
                    this.selectWidget = {}
                } else {
                    this.selectWidget = this.data.list[index - 1]
                }
            } else {
                this.selectWidget = this.data.list[index + 1]
            }

            this.$nextTick(() => {
                this.data.list.splice(index, 1)
            })
        }
    }
}
</script>
<style lang="scss">
    .GridRow{
        .grid-row-item{
            width: calc(100% - 5px);
            height: calc(100% - 5px);
            padding: 5px;
            .el-form-item__content{
                width: 100%;
                height: 100%;
                margin-left: 0 !important;
                .widget-action-delete,.widget-action-clone{
                    bottom: 5px;
                }
            }
        }
        .widget-form-list .widget-view{
            padding: 0 !important;
        }
        .widget-form-container .widget-form-list .widget-action-delete{
            bottom: 0 !important;
        }
    }
</style>
